<?php


namespace catchAdmin\customs\controller;


use cainiao\api\v1\Link;
use catchAdmin\customs\model\HnOrder as hnOrderModel;
use catchAdmin\customs\model\HnOrderDetail as hnOrderDetailModel;
use catchAdmin\customs\model\XsOrder;
use catchAdmin\externalGoods\model\Goods as externalGoodsModel;
use catcher\base\CatchRequest as Request;
use catcher\CatchAuth;
use catcher\CatchResponse;
use houniao\api\v1\Order as HNOrderApi;
use think\facade\Db;
use think\helper\Str;
use xinsheng\api\v1\Pay;
use catchAdmin\api\model\Order as customsOrder;

class XsPay
{

    public function __construct(xsOrder $xsOrder)
    {
        $this->xsOrder  = $xsOrder;
    }

    //列表
    public function index(CatchAuth $auth, Request $request)
    {
        $user = $auth->user();
        return CatchResponse::paginate($this->xsOrder->getList());
    }

    //查询订单报关情况
    public function query($id,CatchAuth $auth, Request $request)
    {
        $queryType =  "1";//单笔查询
        $orderType = $request->get('order_type');//订单类型

        $order  = (new XsOrder)
            ->withoutField('created_at,updated_at,deleted_at,tenant_id,creator_id')
            ->where('id',$id)
            ->find();

        if(!$order){
            return CatchResponse::fail('订单不存在');
        }

        $xinshengApi = new Pay();
        $data = [];
        $data['queryType'] = $queryType;
        $data['orderType'] = $orderType;
        $data['oldMerOrderId'] = $order->merOrderId;

        try {
            $result = $xinshengApi->orderQuery($data);

            return CatchResponse::success($result,'查询成功');
        }catch (\Exception $e ){
            return CatchResponse::fail($e->getMessage());
        }
    }

    //报关申请
    public function customsApply($id,CatchAuth $auth, Request $request)
    {
        $order  = (new customsOrder)
            ->withoutField('created_at,updated_at,deleted_at,tenant_id,creator_id')
            ->where('id',$id)
            ->find();

        if(!$order){
            return CatchResponse::fail('订单不存在');
        }

        $data = $request->post();
        $data['noticeUrl'] = "http://cross.qekj.net/callback/xinsheng";

        $xinshengApi = new Pay();

        try {
            $result = $xinshengApi->customsApply($data);
            $order->customsApply_param = $data;
            $order->customsApply_return = $result['content'];
            $order->customsApply_status = 1;//已申请
            $order->save();

            return CatchResponse::success($result,'提交成功');
        }catch (\Exception $e ){
            return CatchResponse::fail($e->getMessage());
        }
    }
}